define(function(require){
    $(function(){
    	/*---------- 素材管理——平台运营人员+供应商/商铺运营人员 ----------*/
    	
    	/* 表格 */
    	var bodyTemplate = ['<tr material_id="{id}" status="{status}">',
    	                    	'<td class="txtc">{id}</td>',
	    	                    '<td class="txtc">{name}</td>',
	    	                    '<td class="txtc">{tags}</td>',
	    	                    '<td class="txtc">{width}</td>',
	    	                    '<td class="txtc">{height}</td>',
	    	                    '<td class="txtc">{type}</td>',
	    	                    '<td class="txtc">@modifySizeToKB({size})kb</td>',
	    	                    '<td class="txtc"><a href="{landingpage}" target="_blank">{landingpage}</a></td>',
	    	                    '<td class="txtc">{frequency}</td>',
	    	                    '<td class="txtc status" >@materialStatus({status})<input type="hidden" name="reason_" value="{reason}"></td>',
	    	                    '<td class="txtc">',
		                     		'<a class="ibtn previewbtn" href="javascript:;" title="预览"><span class="glyphicon glyphicon-resize-full"></span></a>',
		                     		'<a class="ibtn editbtn" href="javascript:;" title="修改"><span class="glyphicon glyphicon-pencil"></span></a>',
    	                     		/*'<a class="ibtn delbtn" href="javascript:;" title="删除"><span class="glyphicon glyphicon-remove"></span></a>',*/
	                     		'</td>',
		                     '</tr>'].join('');
   
        var grid = Grid.init({
            holder:'materialList',
            bodyTemplate:bodyTemplate,
            dataSource:'/trp/material/get_materials/',
            pageTemplate:semi.grid.pageTemplate,
            sendOnPageSize: true
        });
        
        window.modifySizeToKB=function(size){
    		if(size){
    			size = size *1.0/1024;
    			return size.toFixed(2);
    		}
    		return size;
    		
    	};
    	window.materialStatus=function(status){
    		if(status==0){
    			return '<span class="label label-default" style="font-size:14px;">待审核</span>';
    		}else if(status==1){
    			return '<span class="label label-success" style="font-size:14px;">通过</span>';
    		}else {
    			return '<span class="label label-danger showreason" style="font-size:14px;cursor:pointer;">拒绝</span>';
    		}
    	}
    	grid.onfilled(function(data){
     		grid.data = data;
     		$('.ibtn').tooltip();
     	});
    	
    	//数据搜索
        var filterData = function(pno){
        	var txt = $('.searchbox-ipt').val(),
        		status = $('.pageheader select[name=status]').val(),
        		size = $('.pageheader [name=measure]').val(),
        		type = $('.pageheader [name=type]').val(),
        		width = '', height = '',
            	pageSize = 20;
        	
        	if(size!=-1){
	    		size = size.split('x');
	    		width = size[0];
	    		height = size[1];
	    	}
        	if($('select.page-size').size()>0){
        		pageSize = $('select.page-size').val();
        	}
            grid.send({
        		search_text: txt,
        		status: status,
        		type: type,
        		width: width,
	        	height: height,
        		pageSize: pageSize,
        		pageNo: pno || 1
        	});
        };
        filterData();

        //按尺寸搜索
        $('.pageheader [name=measure]').select2({
        	ajax: {
        		url: '/trp/material/get_material_size/',
        		results: function(data){
        			var resultArr = [];
        			$.each(data.data, function(i,n){
        				var val = n.width+'x'+n.height;
        				resultArr.push({id:val, text:val});
        			});
        			return {results: resultArr}
        		}
        	}
        }).on('change', function(){
        	filterData();
        });
      //按类型搜索
        $('.pageheader [name=type]').select2({
        	ajax: {
        		url: '/trp/material/get_material_type/',
        		results: function(data){
        			var resultArr = [{id:'', text:'全部类型'}];
        			$.each(data.data, function(i,n){
        				resultArr.push({id:n.id, text:n.name});
        			});
        			return {results: resultArr}
        		}
        	}
        }).on('change', function(){
        	filterData();
        });
        
        //按审核状态搜索
        $('.pageheader select[name=status]').on('change', function(){
        	filterData();
        }).select2();
        
        //按ID、名称和标签模糊搜索
        $('.pageheader .searchbox-btn').on('click', function(){
        	filterData();
        });
        $('.pageheader .searchbox-ipt').on('keyup', function(e){
        	if(e.keyCode==semi.keyCode.ENTER){
        		filterData();
        	}
        });
        
        require('validate');
        /* 上传素材-dialog */
        $('.creatematerial').on('click', function(){
        	$dialog({
                title: '新增素材',
                content: $('.pop-creatematerial').clone().show()[0],
                width: '620px',
                onshow: function(){
                	var $dlg = this, $node = $(this.node);
                	
                	var reSize = function(){
                		$dlg.width($('.previewlist',$node).width()+212);
                		$('.uploadercont .form_ctrl',$node).width($('.preview',$node).width()-200);
          	  			$('.mbox',$node).css('border-bottom','2px dashed #ccc');
          	  			$('.mbox:last',$node).css('border-bottom','none');
                	}
                	//成功添加素材到列表
                	var addSuccess = function(up, file, d){
                		//d={name: 'hhh.jpg', url:'http://127.0.0.1:8000/static/trp/images/chart.jpg', landingpage:'', height: 200, width: 200, type: '5', size: 7153}
          	  			seajs.log('执行添加并预览素材:'+d.name+', '+d.url);
          	  			if(semi.utils.isEmpty(d.url)){
          	  				$dialog.alert('上传成功，但保持图片失败，请重试！','warning');
          	  				return;
          	  			}
          	  			d['landingpage'] = $('[name=landingpage]',$node).val();
          	  			d['frequency'] = $('[name=frequency]',$node).val();
              		  
          	  			var tmpl = ['<div class="mbox" style="padding:15px 5px;">',
	              		              	'<div class="mcontent"></div>',
	              		              	'<div style="position:relative;"><span class="block">素材名称：</span><input type="text" name="picname" class="form-control block" placeholder="请填写名称" style="margin:5px 0;" /></div>',
	              		              	'<div style="position:relative;"><span class="block">素材标签：</span><input type="text" name="pictags" class="form-control block" placeholder="请填写标签" style="margin:5px 0;" /></div>',
	              		              	'<div style="position:relative;"><span class="block">链接地址：</span><input type="text" name="piclandingpage" class="form-control block" placeholder="请填写链接地址" style="margin:5px 0;" /></div>',
	              		              	'<div style="position:relative;"><span class="block">频次控制：</span><input type="text" name="picfrequency" class="form-control block" placeholder="请填写频次" style="margin:5px 0;" /></div>',
	              		              	'<button type="button" class="btn btn-danger btn-sm delbtn">移除</button>',
	              		              '</div>'].join('');
	    				/*<input type="hidden" name="picurl"/>
	    				<input type="hidden" name="pictype" />
	    				<input type="hidden" name="picwidth" />
	    				<input type="hidden" name="picheight" />
	    				<input type="hidden" name="picsize" />*/
	          	  		$('.preview',$node).show();
	          	  		$('.previewlist',$node).append(tmpl).find('.mbox:last').data('data',d);
	          	  		
	          	  		var $mbox = $('.mbox:last',$node);
          	  			require.async('./common/showmaterial', function($showmaterial){
          	  				$showmaterial.init({
          	  					item: $('.mcontent',$mbox),
          	  					data: $.extend({},d,{landingpage:''})
          	  				});
          	  				$('[name=pictags]',$mbox).val($('[name=tags]',$node).val());
          	  				$('[name=piclandingpage]',$mbox).val($('[name=landingpage]',$node).val());
          	  				$('[name=picfrequency]',$mbox).val($('[name=frequency]',$node).val());
          	  				$('[name=picname]',$mbox).val(d.name);
          	  				/*$('[name=pictype]',$node).val(d.type);
          	  				$('[name=picwidth]',$node).val(d.width);
          	  				$('[name=picurl]',$node).val(d.url);
          	  				$('[name=picheight]',$node).val(d.height);
          	  				$('[name=picsize]',$node).val(d.size);*/
          	  				reSize();
	          	  			$('.delbtn:last',$node).off('click').on('click', function(){
	          	  				$(this).parents('.mbox:first').slideUp('fast', function(){
	          	  					$(this).remove();
	          	  					reSize();
	          	  					if($('.mbox',$node).size()<1)$('.preview',$node).hide();
	          	  				});
	          	  				$('#' + file.id).remove();
	          	  				up.removeFile(file);
	          	  			});
          	  			});
                	}
                	$('.uploadercont .form_ctrl',$node).width($('.uploadercont',$node).width()-200);
                	$('.previewlist',$node).css('min-width',$('.uploadercont',$node).width()-200+'px');
                	
                	$node.on('focus', '[name=landingpage],[name=piclandingpage]', function(){
                		$(this).removeClass('error').siblings('label.error').remove();
                	});
                	
                	//单文件上传
                    /*require.async('uploadfile', function($uploadfile){
                    	$uploadfile.init({
                        	container: $('.upsinglefile',$node),
                      	  	url: '/trp/material/upload/',
                      	  	vars: {
                      	  		types: '*.jpg;*.bmp;*.gif;*.png;*.swf',
                      	  		maxsize: 1024*5
                      	  	},
                      	  	isdebug: true,
                      	  	success: addSuccess,
                      	  	error: function(data){
                      	  		if(data=='tooLarge'){
                      	  			$dialog.alert('素材文件最大支持 <i><b>5M</b></i> ！','warning');
                      	  		}else{
                      	  			$dialog.alert('上传素材失败，请稍后重试！','warning');
                      	  		}
                      	  	}
                    	});
                    });*/
                    
                    //多文件上传
                	require.async('plupload', function(){
                		$('.uploader',$node).pluploadQueue({
                            runtimes : 'html5,flash,silverlight,html4',
                            url : '/trp/material/upload/',
                            filters : {
                                max_file_size : '5mb',
                                mime_types: [
                                    {title : 'Image files', extensions : 'jpg,bmp,gif,png'},
                                    {title : 'Flsh files', extensions : 'swf'}
                                ]
                                //,prevent_duplicates: true //是否允许重名
                            },
                            multiple_queues: true,
                            flash_swf_url : '/static/common/semidata/gallery/plupload/2.1.2/Moxie.swf',
                            silverlight_xap_url : '/static/common/semidata/gallery/plupload/2.1.2/Moxie.xap',
                            setup: function(uploader){
                            	uploader.bind('FileUploaded', function(up, file, back){
                            		require.async('parsejson', function($parsejson){
                            			addSuccess(up, file, $parsejson(back.response));
                            		});
                        		});
                            	uploader.unbind('Error');
                            	uploader.bind('Error', function(up, err) {
                					var file = err.file;
                					if (file) {
                						if (err.code == plupload.FILE_SIZE_ERROR) {
                							//$dialog.alert(_("Error: File too large:") + " " + file.name,'warning');
                							$dialog.alert('大小错误！素材文件最大支持 <i><b>5M</b></i>','warning');
                						}
                						if (err.code == plupload.FILE_EXTENSION_ERROR) {
                							//$dialog.alert(_("Error: Invalid file extension:") + " " + file.name,'warning');
                							$dialog.alert('格式错误！素材文件类型暂支持以下格式：<br><i><b>JPG, BMP, GIF, PNG, SWF</b></i>','warning');
                						}
                					}
                				});
                            }
                        });
                	});
                	/*$('.upmultiplefil').hoverClass().on('click', function(){
                		$('.uploadercont .form_ctrl',$node).width($('.uploadercont',$node).width()-170);
                		$('.uploadercont',$node).slideToggle('fast');
                	});*/
                },
                okValue: '保存',
                ok: function(){
            		var $dlg = this, $node = $(this.node);
            		if(!$('form',$node).valid())return false;
            		var materialArr = [];
            		$('.mbox',$node).each(function(){
            			var $this = $(this), _d = $this.data('data');
            			//{name: 'hhh.jpg', url:'http://127.0.0.1:8000/static/trp/images/chart.jpg', landingpage:'', height: 200, width: 200, type: '5', size: 7153}
            			materialArr.push({
            				url: _d.url,
          				  	width: _d.width,
          				  	height: _d.height,
          				  	size: _d.size,
          				  	type: _d.type,
          				  	name: $('[name=picname]',$this).val(),
          				  	tags: $('[name=pictags]',$this).val(),
          				  	landingpage: $('[name=piclandingpage]',$this).val(),
          				  	frequency: $('[name=picfrequency]',$this).val()
            			});
            		});
            		if(semi.utils.isEmpty(materialArr)){
            			$dialog.alert('您还未上传任何素材！','warning');
            			return false;
            		}
            		var exUrlArr = [];
            		$('[name=landingpage],[name=piclandingpage]',$node).each(function(){
            			var url = $(this).val();
            			if(!semi.utils.isEmpty(url) && !semi.utils.isGomeUrl(url)){
            				$(this).addClass('error').css('margin-bottom','10px').siblings('label.error').remove();
            				$(this).after('<label class="error" style="position:absolute;top:auto;bottom:-7px;left:71px;">请填写国美站内链接</label>');
            				exUrlArr.push(url);
            			}else{
            				$(this).removeClass('error').siblings('label.error').remove();
            			}
            		});
            		if(!semi.utils.isEmpty(exUrlArr)){
            			return false;
            		}
            		$ajax.ajax({
            			url : '/trp/material/do_create/',
                		data: JSON.stringify({
                			landingpage: $('[name=landingpage]',$node).val(),
                			tags: $('[name=tags]',$node).val(),
                			frequency: $('[name=frequency]',$node).val(),
                			materials: materialArr
                		}),
                		contentType : 'application/json',
                        type : 'POST',
                        dataType : 'json',
                        success: function(){
                        	$dlg.close().remove();
                        	$dialog.alert('上传素材成功！','success');
                        	filterData();
                        },
                    	error: function(){
                      		$dialog.alert('上传素材失败，请稍后重试！','warning');
                      	}
                	});
                	return false;
                },
                cancelValue: '取消',
                cancel: true
            }).showModal();
        });
        
        /* 查看拒绝原因-dialog */
        $(document).on('click', '.status', function(){
        	var $this = $(this), $tr = $this.parents('tr:first'),status = $tr.attr('status'), reason = $('[name=reason_]',$tr).val();
        	console.log(status);
        	console.log(reason);
        	if (status==2)
	        	$dialog({
	                title: '查看拒绝原因',
	                content: $('.pop-refuse').clone().show()[0],
	                width: '500px',
	                onshow: function(){
	                	var $node = $this.node;
	                	if(semi.utils.isEmpty(reason))reason = ' ';
	                	$('[name=reason]',$node).val(reason).attr('readonly','readonly');
	                },
	                cancelValue: '关闭',
	                cancel: true
	            }).showModal();
        });
        
        /* 预览素材-dialog */
        require('./common/popmaterial').init();
        
        /* 编辑素材-dialog */
        require('./common/popmaterial').init({
        	btn: '.editbtn',
        	action: 'edit',
        	success: function(){
        		filterData(semi.utils.gridPage(grid));
        	}
        });
        
        /* 删除素材-dialog */
       /* require('./common/popmaterial').init({
        	btn: '.delbtn',
        	action: 'delete',
        	success: filterData
        });*/
    });
});